<template>
  <a-steps :current="current" size="small">
    <a-step title="原手机号" />
    <a-step title="新手机号" />
    <a-step title="完成" />
  </a-steps>
  <div class="steps-content">
    <a-form
      v-if="current <= 1"
      ref="FormRef"
      layout="horizontal"
      :model="FormState"
      :rules="FormRule"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
    >
      <a-form-item label="原手机号">
        {{ phone }}
      </a-form-item>
      <a-form-item :label="current == 0 ? '原手机号' : '新手机号'" name="phone">
        <a-input v-model:value="FormState.phone" placeholder="请输入完整手机号" />
      </a-form-item>
      <a-form-item label="验证码" name="captcha">
        <a-input v-model:value="FormState.captcha" placeholder="请输入验证码">
          <template #suffix>
            <a-button
              class="getCaptcha"
              tabindex="-1"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              >{{ (!state.smsSendBtn && '获取验证码') || state.time + ' s' }}</a-button
            >
          </template>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          :loading="ConfirmLoading"
          style="margin-left: 18.5%"
          @click="OnSubmit"
        >
          下一步
        </a-button>
      </a-form-item>
    </a-form>
    <div v-else>
      <a-result status="success" title="修改成功" />
    </div>
    <div
      v-if="setting.captcha == 'dragon'"
      id="dragon_captcha"
      class="J__captcha__"
      data-cbfn="callback"
    ></div>
    <TencentCaptcha
      v-if="setting.captcha == 'tencent'"
      ref="Tencent"
      :appId="setting.captcha_app_id"
      @callback="TencSuccess"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, ref, toRaw } from 'vue'
import { getSecuritySetting, changePhone } from '@/api/personal'
import { requestFailed, requestSuccess } from '@/utils/feedback'
import { validateCaptcha, validatePhone } from '@/utils/validate'
import { message, Result } from 'ant-design-vue'
import { getSmsCode } from '@/api/system'
import { getLoginParam } from '@/api/common'

export default defineComponent({
  name: 'PhoneSettings',
  components: {
    [Result.name]: Result
  },
  setup() {
    const FormRef = ref()
    let Tencent = ref<any>(null)
    const state = reactive({
      current: 0,
      phone: '',
      setting: {
        captcha_app_id: '',
        captcha: ''
      },
      ConfirmLoading: false,
      state: {
        smsSendBtn: false,
        time: 60
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    })
    const FormState = reactive({
      phone: '',
      captcha: '',
      token: '',
      authenticate: '',
      current: state.current == 0 ? 'change_phone_old' : 'change_phone_new'
    })
    const FormRule = {
      captcha: [
        { required: true, message: '请填写验证码', trigger: ['blur', 'change'] },
        { validator: validateCaptcha }
      ],
      phone: [
        { required: true, message: '请填写手机号', trigger: ['blur', 'change'] },
        { validator: validatePhone }
      ]
    }

    const initCaptcha = () => {
      new (window as any).Captcha(document.querySelectorAll('.J__captcha__').item(0), {
        // 验证成功时显示
        appId: state.setting.captcha_app_id, //开通后提供
        timerProgressBar: !0, // 是否启用进度条
        timerProgressBarColor: '#07f', // 进度条颜色
        // 验证成回调
        success: function (res) {
          FormState.token = res.token
          getCaptcha()
        },
        // 验证失败回调
        fail: function () {},
        // 触发验证回调, 不管成功与否
        close: function () {}
      })
    }

    const TencSuccess = (info) => {
      FormState.authenticate = info.randstr
      FormState.token = info.ticket
      getCaptcha()
    }

    onMounted(() => {
      getDataList()
      getSetting()
    })
    const getSetting = () => {
      getLoginParam({})
        .then((res) => {
          state.setting = res
        })
        .catch((err) => {
          console.log(err)
        })
    }
    function getDataList() {
      getSecuritySetting({}).then((res) => {
        state.phone = res.phone
      })
    }
    const OnSubmit = () => {
      FormRef.value
        .validate()
        .then(() => {
          changePhone(toRaw(FormState))
            .then((res) => {
              if (res.code === 200) {
                state.current = state.current + 1
                FormRef.value.resetFields()
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.ConfirmLoading = false
            })
        })
        .catch(() => {
          return false
        })
    }
    let interval = window.setInterval(() => {})
    function getCaptcha() {
      if (state.state.smsSendBtn == true) {
        return false
      }
      if (!FormState.phone) {
        requestFailed(null, '请输入手机号')
        return false
      }
      if (
        state.setting.captcha == 'tencent' &&
        (FormState.authenticate == '' || FormState.token == '')
      ) {
        Tencent.value.verifyShow()
        return false
      } else {
        if (state.setting.captcha == 'dragon' && FormState.token == '') {
          initCaptcha()
          return false
        }
      }
      state.state.smsSendBtn = true
      interval = window.setInterval(() => {
        if (state.state.time-- <= 0) {
          state.state.time = 60
          state.state.smsSendBtn = false
          window.clearInterval(interval)
        }
      }, 1000)
      let hide = message.loading('验证码发送中..', 0)
      getSmsCode({
        phone: FormState.phone,
        token: FormState.token,
        authenticate: FormState.authenticate,
        type: state.current == 0 ? 'change_phone_old' : 'change_phone_new'
      })
        .then((res) => {
          setTimeout(hide, 1000)
          if (res.code === 200) {
            requestSuccess(null, '验证码获取成功')
          } else {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.state.time = 60
            state.state.smsSendBtn = false
            requestFailed(res)
          }
        })
        .catch((err) => {
          console.log(err)
          setTimeout(hide, 1)
          clearInterval(interval)
          state.state.time = 60
          state.state.smsSendBtn = false
          requestFailed(err)
        })
    }
    return {
      ...toRefs(state),
      FormState,
      FormRule,
      getCaptcha,
      TencSuccess,
      OnSubmit,
      FormRef
    }
  }
})
</script>

<style lang="scss" scoped>
.steps-content {
  margin-top: 26px;
}
</style>
